﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace TS_XY_Train_Repaire
{
    public partial class LoginForm : DevExpress.XtraEditors.XtraForm
    {
        private bool m_showing = true;
        public LoginForm()
        {
            InitializeComponent();
        }
        private void pb_Login_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            TS_Win_Locomotive_MainForm.htActionItem.Remove(this.Name);
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            Opacity = 0.0;
            Activate();
            Refresh();
            fadeTimer.Start();
            Refresh();
            Init();
            if (cb_Login_SaveAccount.Checked)
            {
                InitAccount();
            }
        }
        private void InitAccount()
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(TS_Win_Class._xml_SysSetting_Filename); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode("//xml_TS_AllInOne//AcountData");//加载用户数据节点
                tb_Login_US.Text = DESEncrypt.Decrypt(xmlNode.ChildNodes.Item(1).InnerText, TS_Win_Class._xml_SysSetting_CompanyName);
                tb_Login_PS.Text = DESEncrypt.Decrypt(xmlNode.ChildNodes.Item(2).InnerText, TS_Win_Class._xml_SysSetting_CompanyName);
                //cb_Login_DepList.Text = xmlNode.ChildNodes.Item(3).InnerText;
                if (tb_Login_US.Text.Trim().Length > 3)
                {
                    string strSQL = "select f_id,((select f_name from TS_S_T_P_RailwayStations where f_id=TS_S_T_P_Stuff.f_rsid)+'/'+(select f_name from TS_S_T_P_Department where f_id=TS_S_T_P_Stuff.f_depid)+'/'+f_name) as f_name from TS_S_T_P_Stuff where f_workercode like '%" + tb_Login_US.Text.Trim() + "%'";
                    TS_Win_Class.FillListTypeAct(cb_Login_DepList, strSQL);
                }
                else
                {
                    cb_Login_DepList.DataSource = null;
                    cb_Login_DepList.Items.Clear();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void Init()
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(TS_Win_Class._xml_SysSetting_Filename); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode("//xml_TS_AllInOne//LocalSetting//SaveAccount");//加载是否保存账号节点
                if (xmlNode.InnerText.Trim() == "0")
                {
                    cb_Login_SaveAccount.Checked = false;
                    cb_Login_AutoLogin.Enabled = false;
                    cb_Login_AutoLogin.Checked = false;
                }
                else
                {
                    cb_Login_SaveAccount.Checked = true;
                    cb_Login_AutoLogin.Enabled = true;
                }
                xmlNode = xmlDoc.SelectSingleNode("//xml_TS_AllInOne//LocalSetting//AutoLogin");//加载是否自动登录节点
                if (xmlNode.InnerText.Trim() == "0")
                {
                    cb_Login_AutoLogin.Checked = false;
                }
                else
                {
                    cb_Login_AutoLogin.Checked = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cb_Login_SaveAccount_CheckedChanged(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(TS_Win_Class._xml_SysSetting_Filename); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode("//xml_TS_AllInOne//LocalSetting//SaveAccount");//加载是否保存账号节点
                if (cb_Login_SaveAccount.Checked)
                {
                    xmlNode.InnerText = "1";
                    cb_Login_AutoLogin.Enabled = true;
                }
                else
                {
                    cb_Login_AutoLogin.Enabled = false;
                    cb_Login_AutoLogin.Checked = false;
                    xmlNode.InnerText = "0";
                    xmlNode = xmlDoc.SelectSingleNode("//xml_TS_AllInOne//LocalSetting//AutoLogin");
                    xmlNode.InnerText = "0";
                }
                xmlDoc.Save(TS_Win_Class._xml_SysSetting_Filename);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cb_Login_AutoLogin_CheckedChanged(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(TS_Win_Class._xml_SysSetting_Filename); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode("//xml_TS_AllInOne//LocalSetting//AutoLogin");//加载是否自动登录节点
                if (cb_Login_AutoLogin.Checked)
                {
                    xmlNode.InnerText = "1";
                }
                else
                {
                    xmlNode.InnerText = "0";
                }
                xmlDoc.Save(TS_Win_Class._xml_SysSetting_Filename);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void bt_Login_Login_Click(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            if ((tb_Login_US.Text.Trim().Length > 0 && tb_Login_PS.Text.Trim().Length > 0 && cb_Login_DepList.SelectedIndex > -1 && cb_Login_SaveAccount.Checked) || (tb_Login_US.Text.Trim().Length > 0 && tb_Login_PS.Text.Trim().Length > 0 && cb_Login_DepList.SelectedIndex > -1 && !cb_Login_SaveAccount.Checked && cb_Login_DepList.SelectedIndex > -1))
            {
                string strSQL = "select top 1 getdate() as F_servertime,*,(select f_name from TS_S_T_P_RailwayStations where f_id=TS_S_T_P_Stuff.f_rsid) as f_rsname,(select f_name from TS_S_T_P_Department where f_id=TS_S_T_P_Stuff.f_depid) as f_depname,(select f_level from TS_S_T_P_Department where f_id=TS_S_T_P_Stuff.f_depid) as f_level,(select f_name from TS_S_T_P_Position where f_id=TS_S_T_P_Stuff.f_posid) as f_posname,(select f_name from TS_S_T_P_RailwayBureau where f_id=TS_S_T_P_Stuff.f_rbid) as f_rbname from TS_S_T_P_Stuff where f_workercode='" + tb_Login_US.Text.Trim() + "' and f_password='" + DESEncrypt.Encrypt(tb_Login_PS.Text.Trim(), TS_Win_Class._xml_SysSetting_CompanyName) + "' and f_del=0";
                //if (cb_Login_SaveAccount.Checked)
                //{
                //    xmlDoc.Load(Ts_All_In_One_Win_Class._xml_SysSetting_Filename); //加载XML文档
                //    XmlNode xmlNode = xmlDoc.SelectSingleNode("//xml_TS_AllInOne//AcountData//AccountID");

                //    strSQL = "select top 1 getdate() as F_servertime,*,(select f_name from TS_S_T_P_RailwayStations where f_id=TS_S_T_P_Stuff.f_rsid) as f_rsname,(select f_name from TS_S_T_P_Department where f_id=TS_S_T_P_Stuff.f_depid) as f_depname,(select f_level from TS_S_T_P_Department where f_id=TS_S_T_P_Stuff.f_depid) as f_level,(select f_name from TS_S_T_P_Position where f_id=TS_S_T_P_Stuff.f_posid) as f_posname,(select f_name from TS_S_T_P_RailwayBureau where f_id=TS_S_T_P_Stuff.f_rbid) as f_rbname from TS_S_T_P_Stuff where f_workercode='" + tb_Login_US.Text.Trim() + "' and f_password='" + DESEncrypt.Encrypt(tb_Login_PS.Text.Trim(), Ts_All_In_One_Win_Class._xml_SysSetting_CompanyName) + "' and f_del=0 and f_id=" + DESEncrypt.Decrypt(xmlNode.InnerText, Ts_All_In_One_Win_Class._xml_SysSetting_CompanyName);
                //}
                //else
                //{
                //    strSQL = "select top 1 getdate() as F_servertime,*,(select f_name from TS_S_T_P_RailwayStations where f_id=TS_S_T_P_Stuff.f_rsid) as f_rsname,(select f_name from TS_S_T_P_Department where f_id=TS_S_T_P_Stuff.f_depid) as f_depname,(select f_level from TS_S_T_P_Department where f_id=TS_S_T_P_Stuff.f_depid) as f_level,(select f_name from TS_S_T_P_Position where f_id=TS_S_T_P_Stuff.f_posid) as f_posname,(select f_name from TS_S_T_P_RailwayBureau where f_id=TS_S_T_P_Stuff.f_rbid) as f_rbname from TS_S_T_P_Stuff where f_workercode='" + tb_Login_US.Text.Trim() + "' and f_password='" + DESEncrypt.Encrypt(tb_Login_PS.Text.Trim(), Ts_All_In_One_Win_Class._xml_SysSetting_CompanyName) + "' and f_del=0 and f_id=" + cb_Login_DepList.SelectedValue.ToString();
                //}
                SqlConnection conn = new SqlConnection(TS_Win_Class.GetSQlConnStr());
                conn.Open();
                SqlCommand comm = new SqlCommand(strSQL, conn);
                SqlDataReader read = comm.ExecuteReader();
                if (read.HasRows)
                {
                    read.Read();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserLoginState = true;
                    TS_Win_Locomotive_MainForm.pUserInfoMain.Username = read["F_name"].ToString().Trim();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserCode = read["f_workercode"].ToString().Trim();
                    if (read["f_level"].ToString().Trim() == ",")
                    {
                        TS_Win_Locomotive_MainForm.pUserInfoMain.UserDepTopID = read["f_depid"].ToString().Trim();
                    }
                    else
                    {
                        string strtopid = read["f_level"].ToString().Trim().Substring(1);
                        strtopid=strtopid.Substring(0,strtopid.IndexOf(","));
                        TS_Win_Locomotive_MainForm.pUserInfoMain.UserDepTopID = strtopid;
                    }
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserDepIndex = read["f_depid"].ToString().Trim();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserDepName = read["f_depname"].ToString().Trim();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserPosID = read["f_posid"].ToString().Trim();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserPosName = read["f_posname"].ToString().Trim();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.GuId = read["F_id"].ToString().Trim();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserRSID = read["F_rsid"].ToString().Trim();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserRSName = read["F_rsname"].ToString().Trim();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.LoginTime = read["F_servertime"].ToString().Trim();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserRBID = read["F_rbid"].ToString().Trim();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserRBName = read["F_rbname"].ToString().Trim();
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserDataRankID = read["F_datarank"].ToString().Trim();
                    if (cb_Login_SaveAccount.Checked)
                    {
                        try
                        {
                            xmlDoc.Load(TS_Win_Class._xml_SysSetting_Filename); //加载XML文档
                            XmlNode xmlNode = xmlDoc.SelectSingleNode("//xml_TS_AllInOne//AcountData//AccountPassword");
                            xmlNode.InnerText = DESEncrypt.Encrypt(tb_Login_PS.Text.Trim(), TS_Win_Class._xml_SysSetting_CompanyName);
                            xmlNode = xmlDoc.SelectSingleNode("//xml_TS_AllInOne//AcountData//AccountID");
                            xmlNode.InnerText = DESEncrypt.Encrypt(read["F_id"].ToString().Trim(), TS_Win_Class._xml_SysSetting_CompanyName);
                            xmlNode = xmlDoc.SelectSingleNode("//xml_TS_AllInOne//AcountData//Account");
                            xmlNode.InnerText = DESEncrypt.Encrypt(read["f_workercode"].ToString().Trim(), TS_Win_Class._xml_SysSetting_CompanyName);
                            xmlNode = xmlDoc.SelectSingleNode("//xml_TS_AllInOne//AcountData//AccountName");
                            xmlNode.InnerText = cb_Login_DepList.Text.Trim();
                            xmlDoc.Save(TS_Win_Class._xml_SysSetting_Filename);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                    if (!TS_Win_Class.WriteAuthorityInXml(TS_Win_Locomotive_MainForm.pUserInfoMain.GuId, TS_Win_Locomotive_MainForm.pUserInfoMain.UserDepIndex, TS_Win_Locomotive_MainForm.pUserInfoMain.UserPosID,TS_Win_Locomotive_MainForm._SysSettings._GetWinFormAuth))
                    {
                        MessageBox.Show("系统权限载入错误，可能隐形部分功能的使用！");
                    }
                    this.Close();
                }
                else
                {
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserLoginState = false;
                    TS_Win_Locomotive_MainForm.pUserInfoMain.Username = "访客";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserCode = "null";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserDepTopID = "null";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserDepIndex = "null";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserDepName = "访客";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserPosID = "null";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserPosName = "访客";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.GuId = "null";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserRSID = "null";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserRSName = "访客";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.LoginTime = "null";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserRBID = "null";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserRBName = "访客";
                    TS_Win_Locomotive_MainForm.pUserInfoMain.UserDataRankID = "null";
                    MessageBox.Show("登录失败，请确认账号和密码正确");
                    TS_Win_Class.DelAuthorityInXml();
                }
                conn.Close();
            }
            else
            {
                MessageBox.Show("请完整填写登录信息！");
            }
        }

        private void fadeTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (m_showing)
            {
                double d = 1000.0 / fadeTimer.Interval / 100.0;
                if (Opacity + d >= 1.0)
                {
                    Opacity = 1.0;
                    fadeTimer.Stop();
                }
                else
                {
                    Opacity += d;
                }
            }
            else
            {
                double d = 1000.0 / fadeTimer.Interval / 100.0;
                if (Opacity - d <= 0.0)
                {
                    Opacity = 0.0;
                    fadeTimer.Stop();
                }
                else
                {
                    Opacity -= d;
                }
            }
        }

        private void tb_Login_US_TextChanged(object sender, EventArgs e)
        {
            if (tb_Login_US.Text.Trim().Length > 3)
            {
                string strSQL = "select f_id,((select f_name from TS_S_T_P_Department where f_id=TS_S_T_P_Stuff.f_depid)+'/'+f_name) as f_name from TS_S_T_P_Stuff where f_del=0 and f_workercode like '%" + tb_Login_US.Text.Trim() + "%'";
//                string strSQL = "select f_id,((select f_name from TS_S_T_P_RailwayStations where f_id=TS_S_T_P_Stuff.f_rsid)+'/'+(select f_name from TS_S_T_P_Department where f_id=TS_S_T_P_Stuff.f_depid)+'/'+f_name) as f_name from TS_S_T_P_Stuff where f_del=0 and f_workercode like '%" + tb_Login_US.Text.Trim() + "%'";
                TS_Win_Class.FillListTypeAct(cb_Login_DepList, strSQL);
            }
            else
            {
                cb_Login_DepList.DataSource = null;
                cb_Login_DepList.Items.Clear();
            }
        }

        private void cb_Login_DepList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cb_Login_DepList.SelectedIndex > -1)
                {
                    pb_Photo.Image = LoadImage(cb_Login_DepList.SelectedValue.ToString());
                }
                else
                {
                    pb_Photo.Image = null;
                }
            }
            catch
            {
            }
        }
        private Image LoadImage(string _ID)
        {
            string str = "";
            Image _img = null;
            str = TS_Win_Class.GetSQlFieldValue("select top 1 f_photo from TS_S_T_P_Stuff_Photo where f_del=0 and f_stuffid=" + _ID, "f_photo");

            try
            {
                if (str.Length > 100)
                {
                    byte[] bt = Convert.FromBase64String(str);
                    System.IO.MemoryStream stream = new System.IO.MemoryStream(bt);
                    Bitmap bitmap = new Bitmap(stream);
                    _img = bitmap;
                }
            }
            catch
            {
            }
            return _img;
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string item = "SystemSettingForm";
            if (TS_Win_Locomotive_MainForm.htActionItem[item] != null)
            {
                try
                {
                    ((SysSetting.SystemSettingForm)TS_Win_Locomotive_MainForm.htActionItem[item]).Focus();
                    ((SysSetting.SystemSettingForm)TS_Win_Locomotive_MainForm.htActionItem[item]).ShowDialog();
                }
                catch (Exception){}
            }
            else
            {
                SysSetting.SystemSettingForm SystemSettingForm = new SysSetting.SystemSettingForm();
                SystemSettingForm.StartPosition = FormStartPosition.CenterScreen;
                TS_Win_Locomotive_MainForm.htActionItem.Add(item, SystemSettingForm);
                SystemSettingForm.Show();
            }
        }
    }
}
